package com.zzdx.deployment.common.file;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.*;

/**
 * @Description 自定义properties文件，解决写入时"\"及":"添加转义字符"\"的问题
 * @Author Mason
 * @Date 2018/12/29
 **/
public class CustomProperties extends Properties {
    private static final long serialVersionUID = 1L;
    /**
     * 按顺序读写key
     */
    private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();
    @Override
    public void store(OutputStream out, String comments) throws IOException {
        customStore(new BufferedWriter(new OutputStreamWriter(out, "utf-8")));
    }

    /**
     * 自定义写入数据，注释saveConvert，处理"\"及":"问题
     * @param bw
     * @throws IOException
     */
    private void customStore(BufferedWriter bw)
            throws IOException {
        bw.write("#" + new Date().toString());
        bw.newLine();
        synchronized (this) {
            for (Enumeration e = keys(); e.hasMoreElements();) {
                String key = (String) e.nextElement();
                String val = (String) get(key);
                // Commented out to stop '/' or ':' chars being replaced
                //key = saveConvert(key, true, escUnicode);
                //val = saveConvert(val, false, escUnicode);
                bw.write(key + "=" + val);
                bw.newLine();
            }
        }
        bw.flush();
    }

    @Override
    public Enumeration<Object> keys() {
        return Collections.<Object> enumeration(keys);
    }

    @Override
    public Object put(Object key, Object value) {
        keys.add(key);
        return super.put(key, value);
    }

    @Override
    public synchronized Object remove(Object key) {
        keys.remove(key);
        return super.remove(key);
    }

    @Override
    public Set<Object> keySet() {
        return keys;
    }

    @Override
    public Set<String> stringPropertyNames() {
        Set<String> set = new LinkedHashSet<String>();
        for (Object key : this.keys) {
            set.add((String) key);
        }
        return set;

    }
}
